<?php

namespace App\Console\Dispatch;


use App\Models\News;
use App\Models\SiteCate;
use App\Models\SiteTagSpider;
use App\Service\Curl;
use Illuminate\Support\Facades\DB;

class Unusualwhales extends Base
{
    /**
     * 请求： https://unusualwhales.com/
     *  sudo -u www php artisan command:dispatch-unusualwhales
     *  sudo -u www php /www/wwwroot/apiasiatechwire/artisan command:dispatch-unusualwhales
     *
     */
    /**
     * 参数与选项的区别
     *      在执行命令时，参数必须严格按定义时的顺序输入，不需输入参数名，只需输入参数的值即可。
     *      输入选项则必须带选项名，且选项名前须加 -- 前缀（选项简写字母前加 -），选项可按任意顺序输入
     */

    // 请求 以及参数
    // protected $signature = 'command:name {param1} {param2}';  // 必填参数
    // protected $signature = 'command:name {参数名?} {参数名=默认值} {参数名? : 参数说明}';  // 可选参数
    // protected $signature = 'command:name {--选项名} {--选项名=} {--选项名=默认值} {--简写字母|选项名} {--选项名 : 选项说明}';  // 选项
    protected $signature = 'command:dispatch-unusualwhales';

    protected $description = '定时任务：从unusualwhales.com快讯数据';  // TODO 定时任务

    // 记录数据量
    protected $numbers;
    protected $strNumber;

    // 执行的命令
    public function handle()
    {
        //$keywords = $this->getKeywords();  // 获取关键词，用于采集快讯的关键词
        //$keywords = $this->getCateKeywords();  // 获取栏目关键词，用于匹配栏目
        $key  = $this->getKey();
        $key  = '5b43b07b6fc93990fc68d90bbf';
        $page = 1;
        if($key != '5b43b07b6fc93990fc68d90bbf'){
            die('key变化');
        }


        // 获取列表
        $domain = 'https://unusualwhales.com';
        $lists  = $this->getArticleLists($key, $page);
        if(!empty($lists)){
            $this->saveList($lists, $domain);
            $this->sqlLog();  // 释放内存
        }


        return $this->showMsg('采集完成！');
    }


    // 保存
    protected function saveList($lists, $domain)
    {
        $field  = 'en_keyword';
        $filter = ["科创板日报", "环球", "详情>>", ">>", '华尔街见闻早餐', '早间要闻汇总'];
        foreach($lists as $key => $item){
            $_id     = $item['id'];
            $_uuid   = $item['uuid'];
            $_slug   = $item['slug'];
            $_c_id   = $item['comment_id'];
            $_tags   = $item['tags'];  // 数组，空数组
            $_title  = $item['title'];  // 标题
            $_html   = $item['html'];   // 详情
            $_desc   = str_replace("\n", "", $item['excerpt']); // 摘要
            $_pic    = $item['feature_image'] ? $domain.$item['feature_image'] : '';
            $_cdate  = $item['created_at'];
            $_mdate  = $item['updated_at'];
            $_pdate  = $item['published_at'];
            $_p_tag  = $item['primary_tag'];
            $_readNo = $item['reading_time'];
            $_readNo = rand(100, 500);

            // 时间是否减少8个小时
            //  同样时间戳，英文站比采集站迟8个小时
            $_ctime = strtotime($item['created_at']);   // 2024-12-11T22:33:36.000+00:00
            $_mtime = strtotime($item['updated_at']);   // 2024-12-11T22:33:36.000+00:00
            $_ptime = strtotime($item['published_at']);   // 2024-12-11T22:33:36.000+00:00


            // 内容对比关键词
            /*$en_keyword = $cateIds = [];
            foreach($keywords as $_word => $cateId){
                if(strpos($_title, $_word) !== false){
                    if(!in_array($_word, $en_keyword)){
                        $en_keyword[] = $_word;
                    }
                    if(!in_array($cateId, $cateIds)){
                        $cateIds[] = $cateId;
                    }
                }
            }*/

            /*// 如果没有匹配到关键词 则不要
            if(empty($en_keyword)){
                continue;
            }*/

            /*// 内容处理
            // 1、添加中国 国家知识产权局      国家信息中心
            $_html = str_replace('国家知识产权局', '中国国家知识产权局', $_html);
            $_html = str_replace('国家信息中心', '中国国家信息中心', $_html);
            // 2、取消来源 最后一位是 ） )
            $_html = $this->removeOrigin($_html);*/

            // 如果超过 500 个字 则不要
            /*if(mb_strlen($content) > 500){
                continue;
            }*/

            // 组合数据
            $row = [
                'title'      => '',
                'desc'       => $_title,
                'images'     => [],
                'is_major'   => 0, // ?
                'verify'     => 1,
                'uid'        => 1,
                'pic'        => $_pic,
                'time'       => $_ctime,
                'url'        => $item['id'],
                'read_no'    => $_readNo,
                'virtual_no' => $_readNo,
                'site'       => 'unusualwhales',
                //'en_keywords' => $en_keyword,
                //'cn_keywords' => $cn_keyword,
            ];

            // 组合数据
            // $insert[] = $row;
            // 保存到数据库
            $this->saveRow($row, $filter, $field);
        }
    }

    // 获取所有的关键词
    protected function getKeywords()
    {
        //$lists = DB::table('site_tag_spider')->get()->toArray();
        $lists = (new SiteTagSpider())->get()->toArray();

        return $lists;
    }

    // 获取文章列表
    protected function getArticleLists($key, $page = 1)
    {
        // https://unusual-whales.ghost.io/ghost/api/v4/content/posts/?key=5b43b07b6fc93990fc68d90bbf&limit=4&include=tags&page=1
        // https://unusual-whales.ghost.io/ghost/api/v4/content/posts/?key=5b43b07b6fc93990fc68d90bbf&limit=4&include=tags&page=3
        $url  = 'https://unusual-whales.ghost.io/ghost/api/v4/content/posts/?key='.$key.'&limit=4&include=tags&page='.$page;
        $curl = new Curl();
        $html = $curl->request($url);
        $json = json_decode($html, true);

        return $json['posts'] ?? [];
    }

    // 获取当天的key
    protected function getKey()
    {
        $url  = 'https://unusualwhales.com/_next/static/chunks/81397-02c0707ad58aa6fa.js';
        $curl = new Curl();
        $html = $curl->request($url);
        $pos1 = strpos($html, '",key:"');
        $html = '{'.substr($html, $pos1 + 2);
        $pos2 = strpos($html, '"}).');
        $html = substr($html, 0, $pos2 + 2);
        $json = json_decode($html, true);  // 返回null

        $str  = 'key:"';
        $sLen = strlen($str);
        $sPos = strpos($html, $str);
        $ePos = strpos($html, '",');
        $html = substr($html, $sPos + $sLen, $ePos - $sPos - $sLen);

        return $html;
    }


}
